import {
  SearchModel
} from "../../models/search.js"
import {
  BookModel
} from "../../models/book.js"
import {
  paginationBeh
} from "../behaviors/pagination-beh.js"
let searchModel = new SearchModel()
let bookModel = new BookModel()
Component({
  /**
   * 组件的属性列表
   */
  behaviors: [paginationBeh], //加入自定义行为
  properties: {
    loadMore: {
      type: String,
      observer: 'loadMore'
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    searchVal: '',
    hotKeys: [],
    historyKeys: [],
    finished: false
  },
  //初始化会执行
  attached() {
    let hotVal = searchModel.getHotList()
    this.setData({
      historyKeys: searchModel.getHistoryList()
    })
    hotVal.then(res => {
      this.setData({
        hotKeys: res.hot
      })
    })
  },
  /**
   * 组件的方法列表
   */
  methods: {
    onCancel() {
      this.initializationData() //清空搜索过的数据
      this.triggerEvent('cancel', {}, {})
    },
    //点击搜索框清除按钮
    onDelete() {
      this.closeSearchLayer()
      this.initializationData() //清空搜索过的数据
    },
    //搜索关键字回车
    onConfirm(event) {
      this.showSearchLayer()
      wx.showLoading()
      this.initializationData() //清空搜索过的数据
      let keyword = event.detail.value || event.detail.text
      this.setData({
        searchVal: keyword
      })
      if (keyword) {
        bookModel.getSearch(keyword, 0).then(res => {
          wx.hideLoading()
          this.setMoreData(res.books)
          this.setTotal(res.total)
          searchModel.setHistory(keyword) //将搜索关键字添加进缓存中
        })
      }
    },
    //加载更多，向下翻页
    loadMore() {
      let keyword = this.data.searchVal
      if (!keyword) return
      if( this.isLocked() ){
        return 
      }
      if (this.hasMore()) {
        this.locked() //请求前加锁
        bookModel.getSearch(keyword, this.getCurrentStart()).then(res => {
          this.setMoreData(res.books)
          this.unLocked()//请求成功后解锁
        },()=>{
          this.unLocked()//请求失败后解锁，比如在无网络的情况下恢复网络
        })
      }
    },
    showSearchLayer() {
      this.setData({
        finished: true
      })
    },
    closeSearchLayer() {
      this.setData({
        finished: false,
        searchVal: ''
      })
    }
   
  }
})